//
//  MoreViewController.m
//  wedding
//
//  Created by 常宽 on 15/1/20.
//  Copyright (c) 2015年 常宽. All rights reserved.
//

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

#import "MoreViewController.h"
#import "HOTDetailsViewController.h"    //下级页面
#import "HotCell.h"         // cell
#import "HomePageModel.h"   //model

@interface MoreViewController ()<PullTableViewDelegate, UITableViewDataSource, UITableViewDelegate>

/// tableView, 热门推荐表视图
@property (nonatomic, retain) CKTableView *hotTableView;
/// 数据数组
@property (nonatomic, retain) NSMutableArray *hotArray;
@property (nonatomic, retain) NSMutableArray *latestArray;
/// tableView, 最新更新表视图
@property (nonatomic, retain) CKTableView *latestTableView;
/// ScrollView
@property (nonatomic, retain) UIScrollView *scrollView;

@end

@implementation MoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 二级页面隐藏tabBar
    self.tabBarController.tabBar.hidden = YES;
    // 重写返回上级页面方法
    UIImage *backImage = [[UIImage imageNamed:@"返回.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem= [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(popBack:)];
    
    self.hotArray = [[NSMutableArray alloc] init];
    self.latestArray = [[NSMutableArray alloc] init];
    
    // 网络请求
    [self netWork];
    // 创建选择视图
    [self creatSegmentView];
    // 创建滚动视图
    [self creatScrollView];
    // 创建tableView,一定在滚动视图下面,因为表视图创建在滚动视图上面
    [self creatTableView];
}
/// 网络请求
- (void)netWork
{
    /// 热门数据的网络请求
    NSString *hot = [NSString stringWithFormat:@"http://circle.halobear.cn/api/mobile/index.php?module=forumdisplay&version=3&fid=2&page=%@&filter=heat&orderby=heats", @"1"];
    [NetHandler networkWithURL:hot completion:^(id result) {
        NSDictionary *dic = [result objectForKey:@"Variables"];
        NSArray *array = [dic objectForKey:@"forum_threadlist"];
        for (NSDictionary *dic0 in array) {
            HomePageModel *model = [[HomePageModel alloc] init];
            [model setValuesForKeysWithDictionary:dic0];
            [self.hotArray addObject:model];
        }
        [self.hotTableView reloadData];
    }];
    
    /// 最新数据的网络请求
    NSString *latest = [NSString stringWithFormat:@"http://circle.halobear.cn/api/mobile/index.php?module=forumdisplay&version=3&fid=2&page=%@&filter=lastpost&orderby=lastpost", @"1"];
    [NetHandler networkWithURL:latest completion:^(id result) {
        NSDictionary *dic = [result objectForKey:@"Variables"];
        NSArray *array = [dic objectForKey:@"forum_threadlist"];
        for (NSDictionary *dic0 in array) {
            HomePageModel *model = [[HomePageModel alloc] init];
            [model setValuesForKeysWithDictionary:dic0];
            [self.latestArray addObject:model];
        }
        [self.latestTableView reloadData];
    }];
    
}
///  刷新方法
static NSInteger hotCount = 2;
- (void)shuaxinHotNetWork
{
    /// 热门数据的网络请求
    NSString *hot = [NSString stringWithFormat:@"http://circle.halobear.cn/api/mobile/index.php?module=forumdisplay&version=3&fid=2&page=%ld&filter=heat&orderby=heats", hotCount];
    [NetHandler networkWithURL:hot completion:^(id result) {
        NSDictionary *dic = [result objectForKey:@"Variables"];
        NSArray *array = [dic objectForKey:@"forum_threadlist"];
        for (NSDictionary *dic0 in array) {
            HomePageModel *model = [[HomePageModel alloc] init];
            [model setValuesForKeysWithDictionary:dic0];
            [self.hotArray addObject:model];
        }
        [self.hotTableView reloadData];
    }];
    hotCount ++;
}
static NSInteger latestCount = 2;
- (void)shuaxinLatestNetWork
{
    /// 最新数据的网络请求
    NSString *latest = [NSString stringWithFormat:@"http://circle.halobear.cn/api/mobile/index.php?module=forumdisplay&version=3&fid=2&page=%ld&filter=lastpost&orderby=lastpost", latestCount];
    [NetHandler networkWithURL:latest completion:^(id result) {
        NSDictionary *dic = [result objectForKey:@"Variables"];
        NSArray *array = [dic objectForKey:@"forum_threadlist"];
        for (NSDictionary *dic0 in array) {
            HomePageModel *model = [[HomePageModel alloc] init];
            [model setValuesForKeysWithDictionary:dic0];
            [self.latestArray addObject:model];
        }
        [self.latestTableView reloadData];
    }];
    latestCount ++;
}
// 返回上级页面
- (void)popBack:(UIBarButtonItem *)sender
{
    [self.tabBarController.tabBar setHidden:NO];
    [self.segCon removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark 创建选择视图及方法
- (void)creatSegmentView
{
    self.segCon = [[UISegmentedControl alloc] initWithItems:@[ @"热门", @"最新"]];
    [self.segCon setFrame:CGRectMake(80, 5, self.view.frame.size.width - 160, 30)];
    /// 默认的模块
    self.segCon.selectedSegmentIndex = 0;
    [self.segCon addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    
    self.segCon.tintColor = [WebColor lightPink];
    
    [self.navigationController.navigationBar addSubview:self.segCon];
}

/// seg选择方法
- (void)segmentAction:(UISegmentedControl *)segment
{
    CGFloat x = self.view.frame.size.width * segment.selectedSegmentIndex;
    [self.scrollView setContentOffset:CGPointMake(x, self.scrollView.contentOffset.y) animated:YES];
}
#pragma mark -
#pragma mark 滚动视图的创建及协议
- (void)creatScrollView
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView.contentSize = CGSizeMake(2 * WIDTH, 0);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.tag = 5132;
    self.scrollView.delegate = self;
    [self.view addSubview:_scrollView];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _scrollView) {
        self.segCon.selectedSegmentIndex = (scrollView.contentOffset.x / self.view.frame.size.width);
    }
}

#pragma mark -
#pragma mark 加载刷新
- (void) refreshHotTable
{
    // 刷新代码放在这
    if (self.hotArray == nil) {
        [self netWork];
    }
    
    self.hotTableView.pullLastRefreshDate = [NSDate date];
    self.hotTableView.pullTableIsRefreshing = NO;
}
- (void) refreshLatestTable
{
    // 刷新代码放在这
    if (self.latestArray == nil) {
        [self netWork];
    }
    
    self.latestTableView.pullLastRefreshDate = [NSDate date];
    self.latestTableView.pullTableIsRefreshing = NO;
}

- (void) loadMoreDataToHotTable
{
    //  加载更多实现代码放在在这
    [self shuaxinHotNetWork];
    self.hotTableView.pullTableIsLoadingMore = NO;
}
- (void) loadMoreDataToLatestTable
{
    //  加载更多实现代码放在在这
    [self shuaxinLatestNetWork];
    self.latestTableView.pullTableIsLoadingMore = NO;
}

#pragma mark -
#pragma mark - PullTableViewDelegate协议

- (void)pullTableViewDidTriggerRefresh:(PullTableView *)pullTableView
{
    switch (pullTableView.tag) {
        case 5130:
        {
            [self performSelector:@selector(refreshHotTable) withObject:nil afterDelay:3.0f];
        }
            break;
        case 5131:
        {
            [self performSelector:@selector(refreshLatestTable) withObject:nil afterDelay:3.0f];
        }
            break;
            
        default:
            break;
    }
}

- (void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    switch (pullTableView.tag) {
        case 5130:
        {
            [self performSelector:@selector(loadMoreDataToHotTable) withObject:nil afterDelay:3.0f];
        }
            break;
        case 5131:
        {
            [self performSelector:@selector(loadMoreDataToLatestTable) withObject:nil afterDelay:3.0f];
        }
            break;
        default:
            break;
    }
}


#pragma 表视图的创建及协议
- (void)creatTableView
{
    self.hotTableView = [[CKTableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT- 64) style:UITableViewStylePlain];
    self.hotTableView.delegate = self;
    self.hotTableView.dataSource = self;
    self.hotTableView.pullDelegate = self;
    self.hotTableView.tag = 5130;
    [self.scrollView addSubview:self.hotTableView];
    
    self.latestTableView = [[CKTableView alloc] initWithFrame:CGRectMake(WIDTH, 0, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    self.latestTableView.delegate = self;
    self.latestTableView.dataSource = self;
    self.latestTableView.pullDelegate = self;
    self.latestTableView.tag = 5131;
    [self.scrollView addSubview:self.latestTableView];
    
    
}
/// 返回row的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 180;
}
/// 返回cell数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (tableView.tag) {
        case 5130:
        {
            return self.hotArray.count;
        }
            break;
        case 5131:
        {
            return self.latestArray.count;
        }
            break;
        default:
            return 0;
            break;
    }
}
/// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (tableView.tag) {
        case 5130:
        {
            HotCell *cell = [tableView dequeueReusableCellWithIdentifier:@"moreHot"];
            if (!cell) {
                cell = [[HotCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"moreHot"];
            }
            cell.model = self.hotArray[indexPath.row];
            return cell;
        }
            break;
        case 5131:
        {
            HotCell *cell = [tableView dequeueReusableCellWithIdentifier:@"moreLatest"];
            if (!cell) {
                cell = [[HotCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"moreLatest"];
            }
            cell.model = self.latestArray[indexPath.row];
            return cell;
        }
            break;
        default:
        {
            UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:@"moreLatest"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"moreLatest"];
            }
            return cell;
        }
            break;
    }
}
///  选中cell执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (tableView.tag) {
        case 5130:
        {
            HomePageModel *model = self.hotArray[indexPath.row];
            NSLog(@"点击了:%@", model.subject);
            
            HOTDetailsViewController *hotDetails = [[HOTDetailsViewController alloc]init];
            hotDetails.HPmodel = model;
            [self.navigationController pushViewController:hotDetails animated:YES];
        }
            break;
        case 5131:
        {
            HomePageModel *model = self.latestArray[indexPath.row];
            NSLog(@"点击了:%@", model.subject);
            
            HOTDetailsViewController *hotDetails = [[HOTDetailsViewController alloc]init];
            hotDetails.HPmodel = model;
            [self.navigationController pushViewController:hotDetails animated:YES];
        }
            break;
            
        default:
            break;
    }
    [self.segCon removeFromSuperview];
}
#pragma mark -


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
